<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use think\exception\ValidateException;

class UserGroup extends BaseController
{
    //
    public function index()
    {
        $this->checkLogin(true);
        $data = \app\model\UserGroup::select();
        return $this->success('success', $data);
    }

    public function read($id)
    {
        $this->checkLogin(true);
        $data = \app\model\UserGroup::find($id);
        if (empty($data)) return $this->error('用户组不存在');
        return $this->success('success', $data);
    }

    public function save()
    {
        $this->checkLogin(true);
        $data = $this->request->post(['name', 'description', 'rules']);
        if (is_array($data['rules'])) $data['rules'] = join(',', $data['rules']);

        try {
            $this->validate($data, \app\validate\UserGroup::class);
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }

        $group = \app\model\UserGroup::where('name', $data['name'])
            ->find();
        if (!empty($group)) return $this->error('用户组已存在');
        $result = \app\model\UserGroup::create($data);
        return $this->success('success', $result);
    }

    public function update($id)
    {
        $this->checkLogin(true);
        $data = $this->request->put(['name', 'description', 'rules', 'status']);
        $group = \app\model\UserGroup::find($id);
        if (empty($group)) return $this->error('用户组不存在');
        $group->save($data);
        return $this->success('用户组编辑成功', $group);
    }

    public function delete($id)
    {
        $this->checkLogin(true);
        \app\model\UserGroup::destroy($id);
        return $this->success('success');
    }

}
